<template>
  <div v-loading="fundLPPayloading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col v-if="!this.$route.query.id" :span="12">
          <el-form-item :label="$t('基金名称')" prop="fundId">
            <MainBodySelect
              v-model="form.fundId"
              parameters="fund"
              :disabled="this.$route.query.id ? true : false"
              @change="fundChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('出资人')" prop="investId">
            <fund-lp-select v-model="form.investId" :fund-id="form.fundId" :disabled="form.id || investIdDisabledStatus" @change="changeCZR()" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('出资人认缴金额') + $t('金额单位')" prop="subscriptionAmount">
            <Money v-model="form.subscriptionAmount" unit="w" :placeholder="$t('出资人认缴金额')" disabled :decimal-places="4" />
          </el-form-item>
        </el-col>
        <el-col v-if="fundDataType === 'fund'" :span="12">
          <el-form-item :label="$t('Call款期次')" prop="callPeriod">
            <el-select
              v-model="form.callPeriod"
              clearable
              :placeholder="$t('Call款期次')"
              :disabled="(form.id !== '' && form.id !== undefined) || investIdDisabledStatus"
              @change="changeCallQc"
            >
              <el-option
                v-for="dict in callPeriodOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('缴款时间')" prop="payDate">
            <DatePicker
              v-model="form.payDate"
              :placeholder="$t('缴款时间')"
            />

          </el-form-item>
        </el-col>
        <el-col v-if="isShowCallInfo" :span="12">
          <el-form-item :label="$t('Call款截止时间')" prop="callDateEnd">
            <DatePicker
              v-model="form.callDateEnd"
              :disabled="true"
              :placeholder="$t('Call款截止时间')"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowCallInfo" :span="12">
          <el-form-item :label="$t('Call款金额') + $t('金额单位')" prop="callMoney">
            <Money v-model="form.callMoney" unit="w" :placeholder="$t('Call款金额')" disabled :decimal-places="4" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowCallInfo" :span="12">
          <el-form-item :label="$t('已缴金额') + $t('金额单位')" prop="callMoney">
            <Money v-model="form.amountPaid" unit="w" disabled :decimal-places="4" />
          </el-form-item>
        </el-col>
        <el-col v-if="isShowCallInfo" :span="12">
          <el-form-item :label="$t('剩余金额') + $t('金额单位')" prop="callMoney">
            <Money
              v-if="form.amountRemaining !== '0' && form.amountRemaining !== 0"
              v-model="form.amountRemaining"
              unit="w"
              :decimal-places="4"
              disabled
            />
            <el-input
              v-if="form.amountRemaining === '0' || form.amountRemaining === 0"
              v-model="form.amountRemaining"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('缴款金额') + $t('金额单位')" prop="payMoney">
            <Money v-model="form.payMoney" unit="w" :placeholder="$t('缴款金额')" :decimal-places="4" @change="checkPayMoney(form.payMoney)" />
          </el-form-item>
        </el-col>
        <!--        <el-col v-if="isRate" :span="12">-->
        <!--          <el-form-item :label="$t('汇率') " prop="exchangeRate">-->
        <!--            <ExchangeRate-->
        <!--              v-model="form.exchangeRate"-->
        <!--              :currency="fundCurr"-->
        <!--              :date="form.payDate"-->
        <!--              :placeholder="$t('汇率')"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <!--        <el-col v-if="isRate" :span="12">-->
        <!--          <el-form-item :label="$t('缴款金额') + $t('RMB') + $t('金额单位')" prop="payMoneyRmb">-->
        <!--            <ExchangeRateMoney-->
        <!--              v-model="form.payMoneyRmb"-->
        <!--              :rate="form.exchangeRate"-->
        <!--              :money="form.payMoney"-->
        <!--              :placeholder="$t('发生金额') + $t('RMB') "-->
        <!--              unit="w"-->
        <!--            />-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
      </el-row>
      <FileTable has-permi="fund:lppayment" :list.sync="form.fileList" data-type="fund_investor_jk" :btn-show="!otherBtnHide" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮的组件-->
      <SaveBtn has-permi="fund:lppayment" :cancel-func="cancel" :cancel-show="!otherBtnHide" :save-show="!otherBtnHide" />
    </div>
  </div>
</template>

<script>
import { saveFundLpPayment, getFundLpPayment, calculationPaymentAmount } from '@/api/fund/lpPayment/fundLpPayment'
import { getFundInvestor } from '@/api/fund/investor/fundInvestor'
import { getFundCallQCByFundId, getAmountByInvestIdCallQcId } from '@/api/fund/callmoney/fundCallMoney'
import MainBodySelect from '@/components/MainBodySelect/index'
import FundLpSelect from '@/components/Select/fundLpSelect'
import { fundDataType, getFundBase } from '@/api/fund/fundBase'
import { getSystemCurrency } from '@/api/system/config'
import { ruoyiFloat } from '@/utils/ruoyi'

export default {
  components: {
    FundLpSelect,
    MainBodySelect
  },
  props: {
    otherBtnHide: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateSpace = (rule, value, callback) => {
      var money = parseFloat(value)
      if (money === 0) {
        return callback(new Error(this.$t('缴款金额不能为0')))
      } else if (value === '' || value === undefined || value === null) {
        return callback(new Error(this.$t('必填信息')))
      } else {
        return callback()
      }
    }
    return {
      // Call款的第几行数据
      fundCallMoneyIndex: undefined,
      // 表单参数
      form: {
        fileList: []
      },
      // 遮罩层
      fundLPPayloading: false,
      isRate: false,
      fundCurr: '',
      defCurr: '',
      // otherBtnHide: false,
      // 表单校验
      rules: {
        payDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        investId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        subscriptionAmount: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        payMoney: [{ required: true, trigger: ['blur', 'change'], validator: validateSpace }],
        fundId: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        currency: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], exchangeRate: [
          { required: true, message: this.$t('必填信息'), trigger: 'blur' }
        ], payMoneyRmb: [
          { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
        ]
      },
      callPeriodOptions: [],
      isShowInput: false,
      isShowCallInfo: false,
      // 第一次不触发fundChange
      flagChange: false,
      // 修改数据时 , 记录当前缴款金额  后面在计算时, 需要去掉这个金额
      currentPayment: 0,
      investIdDisabledStatus: false,
      // 获取基金数据类型，如果是spv则不展示缴款
      fundDataType: 'fund'
    }
  },
  watch: {
    'form.callPeriod': {
      handler(val) {
        if (val === '' || val === undefined) {
          this.isShowCallInfo = false
        }
      }
    },
    'form.fundId': {
      handler(val) {
        if ((this.callPeriodOptions === undefined || this.callPeriodOptions.length <= 0) && (val !== undefined && val !== null && val !== '')) {
          this.initData(this.$route.query.id === undefined ? this.form.fundId : this.$route.query.id)
        }

        if (val) {
          // 获取基金数据类型，如果是spv则不展示缴款
          this.fundChange(this.form.fundId)
        }
      }
    }
  },
  created() {
    if (this.$route.query.id) {
      this.initCurr()
      this.initData(this.$route.query.id)
      this.getFundDataType(this.$route.query.id)
    }
  },
  methods: {
    // 初始化数据
    init(data) {
      this.fundLPPayloading = true
      this.investIdDisabledStatus = false
      if (data != null && data.id !== undefined) {
        getFundLpPayment(data.id).then(response => {
          this.form = response.data
          const callPeriod = this.form.callPeriod
          this.changeCZR().then(() => {
            this.form.callPeriod = callPeriod
          })
          this.fundLPPayloading = false
          if (data !== undefined && data !== '' && data !== null) {
            if (data.id !== undefined && data.id !== '' && data.id !== null) {
              this.changeCallQc()
            }
          }
        })
      } else {
        this.isShowCallInfo = false
        this.reset()
        this.fundLPPayloading = false
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        fundId: this.$route.query.id,
        investId: undefined,
        subscriptionAmount: undefined,
        payDate: undefined,
        // 已缴金额
        amountPaid: undefined,
        // 剩余金额
        amountRemaining: undefined,
        payMoney: undefined,
        callPeriod: undefined,
        callMoney: undefined,
        remark: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        currency: undefined,
        exchangeRate: undefined,
        payMoneyRmb: undefined,
        delFlag: undefined,
        fileList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      if (this.$parent.$parent.fundLpPaymentLoading !== undefined) {
        this.$parent.$parent.fundLpPaymentLoading = false
      } else {
        this.$parent.$parent.formOpen = false
        this.$parent.$parent.reset()
      }
      this.reset()
      if (this.$parent.$parent.formOpen) {
        this.$parent.$parent.formOpen = false
      }
      // else {
      //   this.$parent.$parent.fundLpPaymentLoading = false
      // }
    },
    // 关闭form页面
    closeForm() {
      try {
        this.$parent.$parent.formOpen = false
        // 当前位置在call界面的话 需要将当前Call款期次的删除按钮禁用
        const callList = this.$parent.$parent.fundCallMoneyList
        if (callList.length > 0) {
          callList.forEach(item => {
            if (item.id === this.form.callPeriod) {
              item.buttonDisabledState = true
            }
          })
        }
      } catch (e) {
        console.log(e)
      }
      // 关闭form页面遮罩层
      this.fundLPPayloading = false
      // 关闭form页面
      this.$parent.$parent.fundLpPaymentLoading = false

      // 刷新list页面
      if (this.fundCallMoneyIndex === undefined || this.fundCallMoneyIndex === null || this.fundCallMoneyIndex === '') {
        this.$parent.$parent.getList()
      }
      try {
        this.$parent.$parent.choiceRadio(this.fundCallMoneyIndex, this.form.fundId)
        this.$params.$params.closeForm()
      } catch (e) {
        console.log(e)
      }
    },
    /** 提交按钮 */
    async submitForm() {
      var obj = {}
      await this.checkPayMoney(this.form.payMoney, obj)
      // 如果币种相同汇率等于1 rmb等于基恩
      if (!this.isRate) {
        this.form.exchangeRate = 1
        this.form.payMoneyRmb = this.form.payMoney
      }
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid && obj.result) {
            this.fundLPPayloading = true
            saveFundLpPayment(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess(this.$t('保存成功'))
                this.closeForm()
                resolve()
              } else {
                this.msgError(response.msg)
                this.fundLPPayloading = false
                reject()
              }
              this.fundLPPayloading = false
            }).catch(() => {
              this.fundLPPayloading = false
            })
          } else {
            this.locationError(document)
            reject()
          }
        })
      })
    },
    async changeCZR() {
      this.$nextTick(() => {
        var investId = this.form.investId
        this.isShowCallInfo = false
        this.form.callPeriod = ''
        // this.form.payMoney = undefined
        this.form.callMoney = undefined
        this.form.subscriptionAmount = '0'
        if (investId !== '' && investId !== undefined && investId !== null) {
          getFundInvestor(investId).then(response => {
            this.form.subscriptionAmount = response.data.subscribedAmount
            this.fundLPPayloading = false
          })
        }
      })
    },
    changeCallQc() {
      var callQcId = this.form.callPeriod
      var investId = this.form.investId
      // this.form.callMoney = 0
      // this.form.payMoney = undefined
      if (callQcId !== undefined && callQcId !== '' && callQcId !== null && investId !== undefined && investId !== '' && investId !== null) {
        this.isShowCallInfo = true
        // 赋值Call款截止时间
        this.callPeriodOptions && this.callPeriodOptions.forEach(item => {
          console.dir(item)
          if (item.dictValue === callQcId) {
            this.form.callDateEnd = item.callDateEnd
          }
        })
        getAmountByInvestIdCallQcId(investId, callQcId).then(response => {
          this.form.callMoney = response.data === null ? 0 : response.data.thisCallMoney
          // 显示 本次已缴金额，本次剩余金额
          calculationPaymentAmount(this.form.fundId, investId, callQcId).then(response => {
            this.isShowInput = true
            // 已缴金额
            if (this.form.payMoney === undefined) {
              this.form.payMoney = 0
            }
            this.currentPayment = this.form.payMoney
            if (this.form.id !== undefined && this.form.id !== '') {
              this.form.amountPaid = response.data - this.currentPayment
            } else {
              this.form.amountPaid = response.data
            }
            // 剩余金额
            this.form.amountRemaining = this.form.callMoney - this.form.amountPaid
            // this.form.amountRemaining = this.form.callMoney - response.data
          })
          this.fundLPPayloading = false
        })
      } else {
        this.form.callMoney = undefined
      }
    },
    async checkPayMoney(money, obj) {
      if (obj === undefined) {
        obj = {}
      }
      obj.resultFlag = true
      obj.resultFlag2 = true
      var callMoney = this.form.callMoney
      try {
        callMoney = Number(ruoyiFloat().formatNum(this.form.callMoney).toFixed(4))
      } catch (e) {
        console.log()
        callMoney = this.form.callMoney
      }
      console.log('缴款金额比较:', money, callMoney)
      if (money > callMoney && callMoney !== null) {
        // 与页面上的Call款金额对比
        this.msgError(this.$t('缴款金额不能大于Call款金额'))
        this.form.payMoney = undefined
      } else if (money > this.form.subscriptionAmount) {
        // 与页面上的出资人认缴额对比
        this.msgError(this.$t('缴款金额不能超过出资人的认缴额'))
        this.form.payMoney = undefined
      } else {
        // 所有出资人的缴款总额 + form中的金额 不能大于from中的出资人缴款总额
        if (this.form.investId !== undefined && this.form.investId !== '') {
          await calculationPaymentAmount(this.form.fundId, this.form.investId, 'undefined').then(response => {
            var temp = 0
            if (this.form.id === undefined && this.form.id !== '') {
              temp = money + response.data
            } else {
              temp = response.data - this.currentPayment
            }
            if (parseFloat(this.form.subscriptionAmount) < temp) {
              temp = 0
              try {
                temp = parseFloat(response.data)
              } catch {
                temp = response.data
              }
              var moneyTemp = this.moneyFormat(temp, 'w')
              this.msgError(this.$t('缴款金额不能超过出资人的认缴额,您的缴款金额累计已达:' + moneyTemp))
              this.form.payMoney = undefined
              obj.resultFlag = false
            } else {
              obj.result = obj.resultFlag && obj.resultFlag2
            }
          })
        }
        // 这个期次的缴款额 + form中的缴款金额 不能大于Call款总额
        if (this.form.callPeriod !== null && this.form.callPeriod !== '' && this.form.callPeriod !== undefined) {
          await calculationPaymentAmount(this.form.fundId, this.form.investId, this.form.callPeriod).then(response => {
            var temps = 0
            if (this.form.id === undefined && this.form.id !== '') {
              temps = ruoyiFloat().formatNum(money + response.data).toFixed(4)
            } else {
              temps = ruoyiFloat().formatNum(money + response.data - this.currentPayment).toFixed(4)
            }
            if (callMoney < temps) {
              var moneyTemps = ((response.data - this.currentPayment) / 10000).toFixed(4)
              this.msgError(this.$t('缴款金额不能超过当前期次的Call款金额,Call款金额累计已达: ' + moneyTemps + this.$t('万元')))
              this.form.payMoney = undefined
              obj.resultFlag2 = false
            } else {
              obj.result = obj.resultFlag && obj.resultFlag2
            }
          })
        }
      }
    },
    // 初始化数据
    initData(fundId) {
      this.fundLPPayloading = true
      getFundCallQCByFundId(fundId).then(response => {
        this.callPeriodOptions = response.data
        this.fundLPPayloading = false
      })
    },
    fundChange(val) {
      if (this.flagChange) {
        if (!this.$route.query.id && !this.$route.query.lpId) {
          this.reset()
        }
        this.isShowCallInfo = false
        this.form.fundId = val
      }
      this.flagChange = true
      this.initData(val)
      this.initCurr(val)
    },
    // 初始化币种信息
    async initCurr(val) {
      let param = this.$route.query.id
      if (this.$route.query.id === undefined) {
        param = val
      }
      await getFundBase(param).then(res => {
        this.fundCurr = res.data.currency
      })
      await getSystemCurrency().then(res => {
        if (res.code === 200) {
          this.defCurr = res.data
        } else {
          this.msgError(res.msg)
        }
      })
      this.isRate = this.defCurr !== this.fundCurr
    },
    // 获取基金数据类型，如果是spv则不展示缴款
    getFundDataType(fundId) {
      fundDataType(fundId).then(res => {
        this.fundDataType = res.data
      })
    }

  }
}
</script>
